<template>
  <div class="header" v-if="homeStatus === '2'">
    <img style="width: 20px;height: 24px;vertical-align: middle" src="../../assets/home_logo.png">
    <span style="vertical-align: middle;margin-left: 10px">{{ $productName }}</span>
    <img style="width: 24px;height: 24px;float: right" @click="$router.push('/zMsSEHQAzer')" src="../../assets/home_customer.png">
  </div>
  <div class="wrapper">
    <template v-if="homeStatus !== null">
      <div class="home_wrapper" v-if="homeStatus !== '2'">
        <div class="header" style="background: initial">
          <img style="width: 20px;height: 24px;vertical-align: middle" src="../../assets/home_logo.png">
          <span style="vertical-align: middle;margin-left: 10px">{{ $productName }}</span>
          <img style="width: 24px;height: 24px;float: right" @click="$router.push('/zMsSEHQAzer')" src="../../assets/home_customer.png">
        </div>
        <div class="home">
          <div style="color: #FFFFFF">
            Get the loan in
            <div style="font-weight: 600;font-size: 24px">3 minutes</div>
          </div>
          <div class="amount_box">
            <div class="title_amount">{{ $t('可借金额') }}</div>
            <div style="color: #FFFFFF">
              <span class="amount_text">₱20000</span>
            </div>
          </div>
          <div class="loan_footer">
            <div class="loan_info">
              <div>
                <div style="margin-bottom: 5px;color: #666666">{{ $t('利息') }}</div>
                <div>{{ '<0.3%/day' }}</div>
              </div>
              <div>
                <div style="margin-bottom: 5px;color: #666666">{{ $t('借款天数') }}</div>
                <div>91-180 {{ $t('天') }}</div>
              </div>
            </div>
          </div>
          <div class="apply_btn">
            <!--        没有获取设备信息或者没有计算额度情况下-->
            <van-button
                class="btn_style"
                round
                type="primary"
                v-if="homeStatus === '7' || homeStatus === '8'"
                @click="againUploadInfo">
              <span v-if="homeStatus === '7'">{{ $t('更新信息') }}</span>
              <span v-else>{{ $t('获取额度') }}</span>
            </van-button>
            <van-button v-else class="btn_style" type="primary" :disabled="homeStatus==='3' || homeStatus=== '6'"
                        @click="send_fill_Info" round>
              <span v-show="homeStatus === '1'">Calculate credit limit</span>
              <span v-show="homeStatus === '4'">Continue to receive the quota</span>
              <span v-show="homeStatus === '3'">Try again in {{ homeDayNum }} days</span>
              <span v-show="homeStatus === '5'">Re-apply</span>
              <span v-show="homeStatus === '6'"><span>
            <span style="vertical-align: middle">Amount Calculation</span>
            <img class="home_wait" src="../../assets/home_wait.png">
          </span></span>
            </van-button>
          </div>
        </div>
      </div>
      <div v-else class="product_list" :class="{'product_list_lng':productList.length > 3 }">
        <div class="product_card" v-for="item in  productList" :key="item.productName"
        >
          <div class="product_header">
            <img class="logo" :src="item.logoUrl">
            <div style="margin-top: 10px">
              <span>{{ item.appName }}</span>
            </div>
          </div>

          <div class="product_body">
            <div class="product_info_content">
              <div class="product_info_item">
                <div class="body_title">
                  <div v-if="item.state === 1 || item.state === 5">Loan Amount</div>
                  <div v-else>Amount</div>
                </div>
                <div style="color: #E79A00">
                  <div v-if="item.state === 1 || item.state === 5">₱{{ item.notTotal }}</div>
                  <div v-else>₱{{ item.amount }}</div>
                </div>
              </div>
              <div class="product_info_item" v-if="item.state === 1 || item.state === 5">
                <div class="body_title">{{ $t('还款时间') }}</div>
                <div>{{ item.refundDate }}</div>
              </div>
              <div class="product_info_item" v-else>
                <div class="body_title">{{ $t('利息') }}</div>
                <div>{{ parseFloat((parseFloat(item.interestRate) * 100).toFixed(1)) }}%</div>
              </div>
            </div>
            <div style="margin-top: 10px;">
              <template v-if="item.state===1 || item.state === 5">
                <div style="display: flex;justify-content: center">
                  <van-button v-show="item.isRoll === 1" class="extend_btn" round
                              type="primary" @click="handleExtend(item)">{{ $t('展期') }}
                  </van-button>
                  <van-button class="repayment_btn"
                              :block="false"
                              round
                              @click="goRepay(item)"
                              type="primary">{{
                      $t('还款')
                    }}
                  </van-button>
                </div>
              </template>
              <template v-else-if="item.state===4">
                <div style="text-align: center">
                  <van-button
                      class="withdraw_btn"
                      :disabled="true"
                      type="primary">
                  <span style="padding: 5px 10px">
                    {{
                      $t('放款失败{day}天后再来', {day: item.nextLoanTime})
                    }}
                  </span>
                  </van-button>
                </div>
              </template>
              <template v-else>
                <div style="text-align: center;margin-top: 10px">
                  <van-button
                      v-if="item.state > -1"
                      class="withdraw_btn"
                      round
                      :disabled="item.state === 0 || item.state === 3"
                      @click="applyEffectProduct(item)"
                      type="primary">{{
                      item.state === 0 ? $t('不可提现') : item.state === 3 ? $t('提现中') : $t('提现')
                    }}
                  </van-button>
                  <van-button
                      v-else-if="item.state === -1 || item.state === -2"
                      class="withdraw_btn"
                      round
                      :disabled="limitBtnStatus && limitProductKey=== item.productName"
                      @click="goLimitCalculation(item)"
                      type="primary">

                <span v-if="(limitBtnStatus && item.productName === limitProductKey)"><span
                    style="vertical-align: middle">{{
                    $t('额度计算中')
                  }}</span> <van-loading
                    size="24px" style="vertical-align: middle;display: inline-block" color="#1989fa"/></span>
                    <span v-else>{{
                        $t('重新获取')
                      }}</span>
                  </van-button>
                </div>
              </template>
            </div>

          </div>
        </div>
      </div>
    </template>
    <div class="home_flow_bg" :style="{marginTop:homeStatus === '2' ? '-20px':'0'}">
      <div class="flow_title">{{ $t('只需三步即可获得贷款') }}</div>
      <div class="flow_content">
        <img class="step_slider" src="../../assets/home_step_silder.png">
        <div class="flow_list">
          <div class="flow_item">
            <img class="flow_icon" src="../../assets/home_step1.png">
            <span style="vertical-align: middle">{{ $t('填写信息') }}</span>
          </div>
          <div class="flow_item">
            <img class="flow_icon" src="../../assets/home_step2.png">
            <span style="vertical-align: middle">{{ $t('身份验证') }}</span>
          </div>
          <div class="flow_item">
            <img class="flow_icon" src="../../assets/home_step3.png">
            <span style="vertical-align: middle">{{ $t('获取配额') }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="sec_center">
      <div style="margin-bottom: 15px">Regulatory Partners</div>
      <div>
        <img class="sec_img" src="../../assets/sec_image.png">
      </div>
    </div>
  </div>

  <van-popup v-model:show="applyShow" position="bottom"  >
    <template #default>
      <div class="confirm_loan_box">
        <div class="cell_content_list" style="padding: 20px;margin-top: 20px">
          <!--        账户类型-->
          <div class="cell_content_item">
            <div class="text" style="text-align: left">
              {{ $t('账户类型') }}
            </div>
            <div style="position: relative">
              <input class="input" v-model="bankInfo.accountTypeName" :readonly="true"/>
            </div>
          </div>
          <!--        银行账户-->
          <div class="cell_content_item" @click="selectBankClick">
            <div class="text">
              {{ $t('银行卡号') }}
            </div>
            <div style="position: relative">
              <input class="input" v-model="bankInfo.bankcard" :readonly="true"/>
              <img class="input_icon" src="../../assets/my/input_right.png">
            </div>
          </div>
          <!--        银行名称-->
          <div class="cell_content_item">
            <div class="text">
              {{ $t('银行名称') }}
            </div>
            <div style="position: relative">
              <input class="input" v-model="bankInfo.bankcardName" :readonly="true"/>
            </div>
          </div>
          <div style="margin-top: 20px;text-align: center">
            <van-button class="next_confirm" round style="margin-right: 10%;width: 35%" @click="applyShow = false">{{ $t('取消') }}</van-button>
            <van-button class="next_confirm" round type="primary" @click="confirmLoanProduct" style="width: 35%">{{ $t('提交') }}</van-button>
          </div>
        </div>
      </div>
    </template>
  </van-popup>
  <!--  -->
  <van-action-sheet
      v-model:show="bankCardShow"
      :actions="selectBankList"
      @select="selectBankConfirm"
      :cancel-text="$t('取消')"
      close-on-click-action
  />
</template>

<script>
import {ref, onMounted, reactive,} from 'vue'
import {
  userInfoVerify,
  getHomeUserStatus,
  fetchMyCard,
  upDateMyCard,
  getHomePageProduct,
  applyConfirm,
  fetchLoanProductDetails, getHomepageLimit
} from "@/api/home";
import {fetchUserNewLoan} from '@/api/order'
import {useI18n} from "vue-i18n";
import router from "@/router";
import {Dialog, Toast} from 'vant'
import {useStore} from "vuex";
import {debounce, processNext, formatMoney, deepClone, setResourcesShow, getAndroidUploadResult} from "@/utils/tool"

export default {
  components: {
    [Dialog.Component.name]: Dialog.Component,
  },
  setup() {
    const {t} = useI18n()
    const store = useStore()
    const applyList = ref([])
    const token = localStorage.getItem('token')
    const loanInfo = ref({})
    const orderPopupShow = ref(false)
    const orderId = ref(null)
    const productList = ref([])
    const orderInfo = ref({})
    const loanInfoDetails = ref({})
    const productNameMain = localStorage.getItem('productName')
    const phone = localStorage.getItem('phone')
    const applyShow = ref(false)
    const bankCardShow = ref(false)
    const selectBankList = ref([])
    const homeStatus = ref(null)
    const limitBtnStatus = ref(false)
    const productFeeShow = ref(true)
    const homeDayNum = ref(null)
    const effectProduct = ref({})
    const productInfoShow = ref({})
    const limitProductKey = ref('')
    const bankInfo = reactive({
      bankcardName: null,
      bankcard: null,
      accountTypeName: null
    })
    // 状态-2获取中-1重新获取0不可借1还款期2可提现3体现中4拒绝5逾期
    const getCardList = async () => {
      const res = await getHomePageProduct({productName: productNameMain})
      if (res.code === 1) {
        // 默认取第一位产品做展示
        loanInfo.value = res.data.mainProduct
        productList.value = deepClone(res.data.canBorroweProducts)
        if (token) {
          await fetchLoanOrder()
        }
      }
    }

    //状态, 1表示可额度计算状态, 2有可借产品状态跳转到列表页, 3表示最新一笔拒绝剩余N天可重试状态, 4表示继续获取额度, 5表示重新申请, 6表示额度计算中,7表示用户没上传设备信息，需重新上传 8用户没有计算额度"
    async function getStatus() {
      const res = await getHomeUserStatus()
      if (res.code === 1) {
        homeStatus.value = res.data.status
        homeDayNum.value = res.data.days
        if (homeStatus.value === '2') {
          await getCardList()
        }
      }
      // 清除loading
      store.dispatch('changeLoading', false)
    }

    // 重新上传用户信息
    async function againUploadInfo() {
      if (homeStatus.value === '7') {
        const isResult = await getAndroidUploadResult()
        if (isResult) {
          Toast(t('更新数据成功!'))
        } else {
          Toast(t('更新数据失败'))
        }
        // 通知安卓上传设备信息
      } else {
        router.push('/kxrCNoNoUZ')
      }
    }

    const send_fill_Info = async () => {
      const isResult = await getAndroidUploadResult()
      if (isResult) {
        const res = await userInfoVerify()
        if (res.code === 1) {
          // 校验用户填写状态与 菜单显示隐藏
          localStorage.setItem('userInfoVerify', JSON.stringify(res.data))
          let data = JSON.parse(localStorage.getItem('userInfoVerify'))
          // 是否有在途订单
          const isLoanOrder = () => {
            const {
              ongoingOrder,
              pendingRepayment,
            } = data
            if (ongoingOrder || pendingRepayment) {
              return true;
            }
            return false
          }
          if (isLoanOrder()) {
            Toast({
              message: t('您已经申请过贷款')
            })
            return;
          } else {
            processNext('')
          }
        }
      }
    }

    // 重新获额
    async function goLimitCalculation({productName}) {
      limitProductKey.value = productName
      limitBtnStatus.value = true
      const res = await getHomepageLimit({productName})
      if (res.code === 1) {
        setTimeout(() => {
          limitBtnStatus.value = false
          getCardList()
          Toast(t('额度计算成功'))
        }, 2000)
      } else if (res.code === 6020) {
        const isResult = await getAndroidUploadResult()
        if (isResult) {
          const res = await getHomepageLimit({productName})
          if (res.code === 1) {
            setTimeout(() => {
              limitBtnStatus.value = false
              getCardList()
              Toast(t('额度计算成功'))
            }, 2000)
          }
        }
      }
    }

    // 获取产品信息
    async function getProductInfo() {
      const {loanAmount, loanTerm, productName} = effectProduct.value
      const params = {
        loanAmount, loanTerm, productName,
        productNameMain: productNameMain
      }
      const res = await fetchLoanProductDetails(params)
      if (res.code === 1) {
        loanInfoDetails.value = res.data
        productFeeShow.value = loanInfoDetails.value.oldLoanConfirmShow === 1
      }
    }

    // 申请多产品
    async function applyEffectProduct(product) {
      if (!token) return router.push('/JFLAWJLfjkw')
      if (product.state !== 2) return Toast(t('当前产品不可借'))
      // await getPermission()
      // 是否申请过订单 申请过订单直接首页创建订单
      if (product.isLoanOrder === 2) {
        effectProduct.value = product
        await getBankList()
        await getProductInfo()
        applyShow.value = true
      } else {
        router.push({
          path: '/qdFaOEpQOpE',
          query: {
            productName: product.productName
          }
        })
      }
    }


    /**
     * 获取用户订单信息
     */
    const fetchLoanOrder = async () => {
      const res = await fetchUserNewLoan()
      if (res.code === 1 && res.data) {
        if (res.data.length !== 0) {
          const approvalResult = res.data.approvalResult
          if ([6, 8].indexOf(approvalResult) !== -1) {
            orderPopupShow.value = true
            orderId.value = res.data.loanRecordId
            orderInfo.value = res.data
            if (res.data.refundDate) {
              const dateArr = new Date(res.data.refundDate).toDateString().split(' ')
              orderInfo.value.dateStr = dateArr[1].trim() + ' ' + dateArr[2].trim()
            }
          }
        }
      }
    }

    // 申请订单提交
    async function confirmLoanProduct() {
      const isResult = await getAndroidUploadResult()
      if (isResult) {
        Toast.loading({
          duration: 0,
          message: t('加载中'),
          forbidClick: true,
        })
        // 设置当前选中的银行卡为默认
        await onDefaultSelect()
        const params = {
          productName: effectProduct.value.productName,
          productNameMain: productNameMain
        }
        const res = await applyConfirm(params)
        if (res.code === 1) {
          Toast({
            message: t('提交成功')
          })
          effectProduct.value = {}
          getCardList()
          Toast.clear()
          localStorage.setItem('orderId', res.data)
          applyShow.value = false
        } else if (res.code === 6020) {
          const isResult = await getAndroidUploadResult()
          if (isResult) {
            goLimitCalculation({productName: effectProduct.value.productName})
            applyShow.value = false
          }
        }
      }
    }

    // 点击切换银行卡
    function selectBankClick() {
      console.log(bankInfo)
      bankCardShow.value = true
      selectBankList.value = selectBankList.value.map(item => {
        item.name = item.bankcard
        item.subname = item.bankcardName
        item.disabled = bankInfo.bankcard === item.bankcard
        return item
      })
    }

    // 选中银行卡
    function selectBankConfirm(value) {
      bankInfo.bankcardName = value.bankcardName
      bankInfo.bankcard = value.bankcard
      bankInfo.accountTypeName = value.accountTypeName
    }

    // 设置银行卡为默认收款银行
    async function onDefaultSelect() {
      console.log(selectBankList.value, bankInfo)
      const info = selectBankList.value.find(v => v.bankcard === bankInfo.bankcard)
      const params = {
        ...info,
        isSelected: 1,
      }
      await upDateMyCard(params)
    }

    // 跳转展期
    async function handleExtend(info) {
      router.push({
        path: '/AAHdUmpZXl',
        query: {
          loanRecordId: info.loanRecordId,
          appName: info.appName,
          type: 'extend'
        }
      })
    }

    //  去还款
    function goRepay(info) {
      router.push({
        path: '/JkGQsgTJyZ',
        query: {
          loanRecordId: info.loanRecordId,
          appName: info.appName,
          type: 'repay'
        }
      })
    }

    // 获取银行卡列表
    async function getBankList() {
      const res = await fetchMyCard()
      if (res.code === 1) {
        if (res.data.length !== 0) {
          selectBankList.value = res.data.sort((a, b) => b.isSelected - a.isSelected).map(item => {
            item.accountTypeName = item.accountType === 1 ? t('电子钱包') : t('银行卡')
            return item
          })
          bankInfo.bankcardName = res.data[0].bankcardName
          bankInfo.bankcard = res.data[0].bankcard
          bankInfo.accountTypeName = res.data[0].accountTypeName
        }
      }
    }

    onMounted(() => {
      setResourcesShow(8).then(res => {
        productInfoShow.value = res
      })
      getStatus()
    })
    return {
      handleExtend,
      goLimitCalculation,
      limitProductKey,
      limitBtnStatus,
      goRepay,
      selectBankList,
      applyShow,
      productList,
      loanInfo,
      homeStatus,
      homeDayNum,
      orderId,
      orderPopupShow,
      send_fill_Info,
      applyList,
      confirmLoanProduct,
      selectBankConfirm,
      selectBankClick,
      applyEffectProduct,
      againUploadInfo,
      productFeeShow,
      orderInfo,
      bankInfo,
      bankCardShow,
      phone,
      loanInfoDetails,
      productInfoShow
    };
  },
}
</script>

<style lang="less" scoped>
.header {
  box-sizing: border-box;
  padding: 15px;
  font-size: 18px;
  background-color: #15B3B2;
  width: 100%;
  color: #FFFFFF;
}

.wrapper {
  margin-top: -5px;
  background-color: #F7F7F7;
}
.confirm_loan_box {
  max-height: 500px;
  overflow: auto;
  padding: 10px 0;
  box-sizing: border-box;
  background-color: #F7F7F7;
}
::v-deep .van-button--disabled {
  opacity: 1 !important;
  background-color: #BCBCBC;
  color: #fff;
  border-color: #BCBCBC;
}

.fee_content {
  font-size: 11px;
  margin-top: 25px;
  padding: 0 20px;
  line-height: 20px;
  color: #a8a8a8;
}

.add_card_text {
  text-align: center;
  font-size: 14px;
  margin-top: 20px;
  color: #FF7805;
  height: 25px;
  line-height: 25px;
}

.home_wrapper {
  background-image: url("../../assets/home_bg.png");
  background-size: 100% 100%;
  height: 400px;
  box-sizing: border-box;
  padding-top: 20px;
  width: 100%;

  .home {
    box-sizing: border-box;
    background-size: 100% 100%;
    color: #333333;
    font-size: 16px;
    position: relative;
    text-align: center;

    .amount_box {
      border-radius: 16px;
      color: #FFFFFF;
      padding: 15px 20px;

      .title_amount {
        margin-bottom: 10px;
        color: #666666;
      }

      .amount_text {
        font-size: 40px;
        font-weight: 600;
        color: #E79A00;
      }

    }

    .loan_footer {
      width: 100%;
      box-sizing: border-box;
      padding: 10px 0;
      border-radius: 0 0 10px 10px;

      .loan_info {
        text-align: center;
        display: grid;
        grid-template-columns: 1fr 1fr;
        font-size: 16px;
        line-height: 22px;
        color: #FFFFFF;
      }
    }


    .apply_btn {
      width: 100%;
      box-sizing: border-box;
      margin-top: 10px;
      color: #333333;
      padding: 10px 25px;

      .btn_style {
        width: 100%;
        font-size: 18px;
        background-color: #FF7809;
        color: #FFFFFF;
      }

      .home_wait {
        width: 20px;
        height: 20px;
        vertical-align: middle;
        margin-left: 7px;
      }
    }

  }
}

.product_list {
  background-color: #15B3B2;
  padding: 20px 10px;
  width: 100%;
  box-sizing: border-box;

  .product_card {
    border-radius: 8px;
    box-sizing: border-box;
    margin-bottom: 20px;
    font-size: 20px;
    background-image: url("../../assets/product_card.png");
    background-size: 100% 100%;
    padding: 10px 10px 16px 10px;

    .product_header {
      padding: 5px 0;
      text-align: center;
      margin-bottom: 10px;

      .product_icon {
        height: 60px;
        width: 40px;
      }

      .is_disabled {
        opacity: 0.5;
      }
    }

    .logo {
      height: 36px;
      width: 36px;
      vertical-align: middle;
      border-radius: 50%;
    }

    .product_body {
      margin-top: 10px;
      font-size: 16px;

      .product_info_content {
        display: grid;
        grid-template-columns: 1fr 1fr;
      }

      .product_info_item {
        padding: 5px 0;
        color: #666666;
        text-align: center;
        font-size: 16px;
      }

      .body_title {
        margin-bottom: 10px;
      }
    }

    .product_apply {
      width: 120px;
    }

  }
}

.confirm_loan_box {
  max-height: 500px;
  overflow: auto;
  padding: 10px 0;
  box-sizing: border-box;
}

.withdraw_btn {
  margin: 0 auto;
  width: 100%;
  font-size: 16px;
}


.home_flow_bg {
  width: 100%;
  text-align: center;
  font-size: 15px;
  box-sizing: border-box;
  border-radius: 10px;
  padding-bottom: 10px;
  position: relative;
  z-index: 10;
  background-color: #F7F7F7;
  padding: 10px 0;

  .flow_title {
    color: #15B3B2;
    padding: 10px 0;
    margin: 0 30px;
    border-radius: 0 0 6px 6px;
    font-size: 16px;
  }

  .flow_content {
    position: relative;
    margin-top: 15px;
    padding: 0 15px;

    .step_slider {
      position: absolute;
      width: 10px;
      height: 173px;
      left: 20px;
    }
  }

  .flow_list {
    font-size: 14px;
    text-align: left;
    padding-left: 30px;

    .flow_item {
      padding: 10px;
      background-color: #FFFFFF;
      margin-bottom: 20px;
      box-shadow: 0px 0px 4px 0px rgba(102, 102, 102, 0.3);
      border-radius: 10px;
    }

    .flow_icon {
      height: 25px;
      width: 25px;
      vertical-align: middle;
      margin-right: 15px;
    }

    .right_icon {
      height: 18px;
      width: 18px;
      padding-top: 10px
    }
  }

}

.sec_center {
  font-size: 16px;
  position: relative;
  text-align: center;
  color: #15B3B2;
  padding: 10px;
  background-color: #F7F7F7;

  .sec_img {
    width: 100%;
    height: 137px;
  }
}

.carousel {
  font-size: 14px;
  background-color: #FFFFFF;
  border-radius: 8px;

  .carousel_item {
    width: 100%;
    padding: 20px 15px;
    box-sizing: border-box;
    line-height: 24px;

    .carousel_item_icon {
      height: 36px;
      width: 36px;
      vertical-align: middle;
    }
  }
}

.is_block {
  width: 50%;
  margin: 0 auto
}

.extend_btn {
  background-color: transparent;
  color: #15B3B2;
  border: 1px solid #15B3B2;
  margin-right: 20px;
  padding: 0 25px;
  position: relative;
}

.extend_tips {
  position: absolute;
  top: -24px;
  left: -10px;
  height: 24px;
  width: 180px;
}
</style>
